package com.epam.productxslt.command;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import com.epam.productxslt.controller.RequestContent;
import com.epam.productxslt.exception.ProductException;
import com.epam.productxslt.transformation.StylesheetCache;

public final class AddGoodsCommand implements Command {

	@Override
	public void execute(RequestContent requestContent) throws ProductException {
		try {
			Transformer transformer = StylesheetCache.newTransformer(RequestContent.ADD_GOODS_XSL_PATH);
			transformer.setParameter(CATEGORY_NAME_PARAMETER, requestContent.getRequestParameter(CATEGORY_NAME_PARAMETER));
			transformer.setParameter(SUBCATEGORY_NAME_PARAMETER, requestContent.getRequestParameter(SUBCATEGORY_NAME_PARAMETER));
			lock.readLock().lock();
			try{
				transformer.transform(new StreamSource(RequestContent.XML_PATH), new StreamResult(requestContent.getResponseWriter()));
			} finally {
				lock.readLock().unlock();
			}			
		} catch (TransformerException e) {
			throw new ProductException(e);
		} 
	}

}
